<template>
  <view class="pay">
    <view class="optadress">
      <!-- 地址为空 -->
      <!-- 支付状态 -->
      <view class="adress" v-if="address">
        <view class="top" @tap='collect'>{{address.provinceName}}{{address.cityName}}{{address.countyName}}{{address.detailInfo}}</view>
        <view class="bottom">
          <view class="user">{{address.userName}}</view>
          <view class="phone">{{formatPhone(address && address.telNumber)}}</view>
        </view>
      </view>
      <block v-else>
      <button v-if="readAdress" @tap='collect'>选择地址</button>
      <button v-else open-type="openSetting" @opensetting="settingCallback">授权读取地址</button>
      </block>
    </view>
    <view class="list">
      <view class="select">已选商品</view>
    <view class="record">
      <view class="item" v-for="item in ProductsList" :key="item.goods_id">
        <view class="left">
          <image :src="item.goods_small_logo"></image>
        </view>
        <view class="right">
          <view class="title">
            {{item.goods_name}}
          </view>
          <view class="info">
            <view class="price">￥{{item.goods_price}}</view>
            <view class="num">x{{item.counter}}</view>
          </view>
        </view>
        </view>
    </view>
    </view>
    <view class="footer">
      <view class="left">
        <view class="text">合计:</view>
        <view class="money">￥{{allMoney}}</view>
      </view>
      <view class="right">
        <view @tap="pay" class="payment" :class="address?'':'disable'">去支付({{allCount}})</view>
      </view>
    </view>
  </view>
</template>

<script>
import http from '@/utils/http';
export default {
  data(){
    return{
      //读取用户地址
      readAdress:true,
      address:null,
      //结算的商品数据
      ProductsList:[],
      allCount :0,
    }
  },
  //计算总价格
  computed:{
    allMoney(){ 
      let allMoney=0;
      let allCount=0;
      this.ProductsList && this.ProductsList.forEach(item=>{
        allMoney += item.counter * item.goods_price;
        allCount += item.counter;
      })
      this.allCount=allCount;
      return allMoney;
    }
  },
  async onLoad(){
    //获取结算商品数据
    this.getProductsList();
    this.initAddress();
  },
  methods:{
    formatPhone(phone){
      // console.log(phone,'123');
       if(phone){
         let startStr = phone.substr(0,5);
         let endStr = phone.substr(-3,3);
         return `${startStr}***${endStr}`;
		  }
    },
    //获取商品数据
    getProductsList(){
      //从本地储存获取购物车数据
      const cart=uni.getStorageSync('cart');
      //筛选勾选按钮的
      this.ProductsList=cart.filter(item=>{
        return item.checked;
      })
      console.log(this.ProductsList);  
    },
    // 点击选择地址
    collect(){
      uni.chooseAddress({
        success:(e)=>{
          //点击确定把地址渲染到页面
          this.address=e;
          // console.log(e);
          this.saveAddress(e);
        },
        //假如用户点击取消会进入这个方法
        fail:(e)=>{
          // console.log(e);
          if(e.errMsg === 'chooseAddress:fail auth deny'){
            this.readAdress=false;
          }
        }
      })
    },
    saveAddress(e){
      uni.setStorageSync('address',e)   
    },
    //读取本地储存
    initAddress(){
      this.address=uni.getStorageSync('address')
    },
    //用户点击授权地址
    settingCallback(e){
      console.log(e);
      this.readAdress=e.detail.authSetting['scope.address'];
    },
    //微信支付
    async pay(){
      const { provinceName, cityName, countyName, detailInfo} = this.address;
      const city = `${provinceName}${cityName}${countyName}${detailInfo}`;
      const goods = this.ProductsList.map(item => {
        return { goods_id: item.goods_id, goods_number: item.counter, goods_price: item.goods_price }
      })
      const token = uni.getStorageSync('token');
      // 生成订单
			const orderRes = await http.post('/my/orders/create', {order_price: this.allMoney, city, goods}, token)
      console.log(orderRes);
      	// 生成预支付
			const prePayRes = await http.post('/my/orders/req_unifiedorder', { order_number: orderRes.order_number }, token);
      console.log(prePayRes);
      const { nonceStr, paySign, signType, timeStamp } = prePayRes.pay;
      console.log(nonceStr, paySign, signType);
      const [error, payRes] = await uni.requestPayment({
				nonceStr,
				package: prePayRes.pay.package,
				paySign,
				signType,
				timeStamp
      })
      //支付成功，跳转页面
      console.log(error, payRes)
      if(!error){
        uni.showToast({
					title: '支付成功！'
        })
        setTimeout(()=>{
        	uni.redirectTo({
						url: '/pages/order/index'
					})	
        },2000)
        this.clearHasPayProduct()
      }
    },
    // 清除购物车勾选的商品
    clearHasPayProduct() {
      const cart = uni.getStorageSync('cart');
      // 获取购物车中选中状态为未选的商品
      const newCart = cart.filter(item => {
        return !item.checked
      })
      uni.setStorageSync('cart', newCart);
      }
    }
}
</script>

<style lang="less">
body{
  background-color: #f9f9f9;
}
.pay{
  height: 100vh;
  .optadress{
    display: flex;
    justify-content: center;
    align-items: center;
    // width: 711rpx;
    height: 187rpx;
    background-color: #fff;
    margin: 21rpx 19rpx 35rpx 20rpx;
    button{
      width: 303rpx;
      height: 89rpx;
      border-radius: 44rpx;
      font-weight: 700;
      color: #ea4b57;
      font-size: 30rpx;
      border: 1rpx solid #ea4b57;
    }
    .adress{ 
      position: absolute;
      left: 46rpx;
      top: 42rpx;
      .top{
        font-weight: bold;
      }
      .bottom{
        display: flex;
        margin-top: 30rpx;
        .user{
          font-size: 26rpx;
        }
        .phone{
          font-size: 26rpx;
          margin-left: 25rpx;
        }
      }
    }
  }
  .list{
    width: 711rpx;
    // height: 489rpx;
    background-color: #fff;
    margin: 35rpx 20rpx 0 20rpx;
    .select{
      margin-left: 17rpx;
      color: #575757;
      line-height: 71rpx;
      font-size: 24rpx;
      font-weight: bold;
    }
    .record{
      .item{
        display: flex;
        width: 698rpx;
        height: 209rpx;
        margin-left: 17rpx;
        .left{
          image{
            width: 191rpx;
            height: 191rpx;
          }
        }
        .right{
          display: flex;
          justify-content: space-between;
          flex-direction: column;
          margin-left: 20rpx;
          padding-right: 30rpx;
          .title{
          margin-top: 15rpx;
          font-size: 27rpx;
        }
          .info{
            display: flex;
            justify-content: space-between;
            margin-bottom: 35rpx;
            .price{
              color: #f3959c;
              font-size: 22rpx;
              font-weight: bold;
            }
            .num{
              font-size: 26rpx;
            }
          }
        }
        }
      }
    }
    .footer{
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 83rpx;
      background-color: #fff;
      padding: 0 28rpx;
      .left{
        display: flex;
        align-items: center;
        .text{
          font-size: 24rpx;
        }
        .money{
          color: #f07b84;
          font-size: 28rpx;
          margin-left: 15rpx;
          font-weight: bold;
        }
      }
      .right{
        .payment{
          width: 150rpx;
          height: 52rpx;
          text-align: center;
          line-height: 52rpx;
          border-radius: 26rpx;
          font-size: 20rpx;
          background-color: #e7404e;
          color: #fff;
        }
        .payment.disable{
          background-color: #B6B6B6;
        }
      }
    }
}
</style>